/**
 * Author  : DAMMAK Wassim
 * Contact : wdammak@talend.com
 * Date    : 12/2008
 * @copyright talend.com 2008
 * @license GNU/GPL Version 2
 **/  
var select_item;
var groupe;

var unicode_or_utf8="unicode"; //Values: unicode || utf8

function stripslashes( str ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
 
    return (str+'').replace(/\0/g, '0').replace(/\\([\\'"])/g, '$1');
}

function addslashes(str) {
	str=str.replace(/\'/g,'\\\'');
	str=str.replace(/\"/g,'\\"');
	str=str.replace(/\\/g,'\\\\');
	str=str.replace(/\0/g,'\\0');
	return str;
}

function stripslashes2(str) {
	str=str.replace(/\\'/g,'\'');
	str=str.replace(/\\"/g,'"');
	str=str.replace(/\\\\/g,'\\');
	str=str.replace(/\\0/g,'\0');
	return str;
}

function serialize2( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

function serialize( mixed_value ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
 
    var _getType = function( inp ) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            if (match = cons.match(/(\w+)\(/)) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "undefined":
            val = "N";
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            val = "s:" + mixed_value.length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key) : key);
                vals += serialize(okey) +
                        serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
    }
    if (type != "object" && type != "array") val += ";";
    return val;
}

function utf8_encode ( string ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
 
    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}

function base64_encode( data ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Tyler Akins (http://rumkin.com)
    // +   improved by: Bayron Guevara
    // +   improved by: Thunder.m
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   bugfixed by: Pellentesque Malesuada
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // *     example 1: base64_encode('Kevin van Zonneveld');
    // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
 
    // mozilla has this native
    // - but breaks in 2.0.0.12!
    //if (typeof window['atob'] == 'function') {
    //    return atob(data);
    //}
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = ac = 0, enc="", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data = utf8_encode(data+'');
    
    do { // pack three octets into four hexets
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
 
        bits = o1<<16 | o2<<8 | o3;
 
        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;
 
        // use hexets to index into b64, and append result to encoded string
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
 
    return enc;
}

function selectAll(liste){
	  var tempval=getElement(liste);
	  tempval.focus();
	  tempval.select();			  
	 
	 var code = tempval.value;

	 code = code.replace(/<.*?>/g,"");
	 code = code.replace(/&lt;/g,"<");
	 code = code.replace(/&gt;/g,">");
	 window.clipboardData.setData("text",code);
}

		
if(!window.clipboardData) {
	window.clipboardData = {
		setData : function(mode,content) {
			var clipboard = document.body;
			var flashclipboard = clipboard.flashclipboard;
			if(flashclipboard == null) {
				flashclipboard = document.createElement('div');
				clipboard.flashclipboard = flashclipboard;
				clipboard.appendChild(flashclipboard);
			}
			flashclipboard.innerHTML = '<embed src="includes/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(content)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
		}
	}
}

//start post
function check(){
	if(document.forms['babili'].selectShow.value=="by_author" && getElement('translated_by_user').className!=""){
		if(typeof(getElement('translated_by_user'))!='undefined' ){
			getElement('translated_by_user').className="";
		}
		getElement('selected_file').className="cachediv";
	}else if(document.forms['babili'].selectShow.value=="order_by_files" && getElement('selected_file').className!=""){
		if(typeof(getElement('translated_by_user'))!='undefined' ){
			getElement('translated_by_user').className="cachediv";
		}
		getElement('selected_file').className="";		
	}else{
		document.forms['babili'].submit();
	}
}

// return Element by id	
function getElement(id){
	var objElm;
	if(document.getElementById && document.getElementById( id  ) ){ // Pour les navigateurs rcents
		objElm= document.getElementById( id );
	}else if(document.all && document.all[ id ]){ // Pour les veilles versions
		objElm=  document.all[ id ];
	}else if(document.layers && document.layers[ id ] ){ // Pour les trs veilles versions
		objElm= document.layers[ id ];
	}else{
		return objElm;
	}
	return objElm;
}

//Return key_name by index_key
function getIdKeyName(index_key){
	for(x in arr) {
		if(arr[x]['0'][3]==index_key ){ 
			return x;
		}
	}
}

//Return key_ref by index_key
function getKeyRef(index_key){
	for(x in arr) {
		if(arr[x]['0'][3]==index_key ){ 
			return arr[x][1][0];
		}
	}
}

//Return key_name by index_key
function getKeyName(index_key){
	for(x in arr) {
		if(arr[x]['0'][3]==index_key ){ 
			return arr[x][0][0];
		}
	}
}

//Return getLigne by index_key
function getLineValues(index_key){
	for(x in arr) {
		if(arr[x]['0'][3]==index_key ){ 
			return arr[x];
		}
	}
}

//set active cell
function selectItem(key_word,num_item,old_num_item){	
	if(!select_item) select_item=old_num_item;
	old_num_item= select_item;
	if(num_item!=select_item){//Eviter la slection d'un item dj slectionn
		tr_selected= getElement(num_item);		
		old_tr_selected= getElement(select_item);
		if(tr_selected) {//modifier le style de l'item selectionn
			tr_selected.className='cell_on';
			select_item= num_item;
			getElement('item_select').value=num_item;
			setSessionValue('item_select',num_item);
		}
		if(old_tr_selected){//modifier le style de l'ancien item
			if(old_num_item % 2){
				old_tr_selected.className='row0';
			}else{
				old_tr_selected.className='row1';
			}
			
		}
	}
	changeItems(num_item);
	changeGlossary(num_item);
}

// retourne un objet xmlHttpRequest.
// mthode compatible entre tous les navigateurs (IE/Firefox/Opera)
function getXMLHTTP()
{
	var xhr = null;
	if(window.XMLHttpRequest){ // Firefox et autres
		xhr = new XMLHttpRequest();
	}else if(window.ActiveXObject){ // Internet Explorer
		try{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(e){
			try{
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e1){
				xhr = null;
			}
		}
	}else{ // XMLHttpRequest non support par le navigateur
		alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
	}
	return xhr;
}


//Function to save\validate\refuse Translation
function saveTransWord(param){
	select_item=parseInt(getElement('item_select').value);
	var tab = getLineValues(select_item);
	id_key=getIdKeyName(select_item);
	
	//Get value is Without propagation
	var without_propagation=getElement('without_propagation');	
	if(typeof(without_propagation)!='undefined'){
		without_propagation=without_propagation.checked;
	}else{
		without_propagation=false;
	}

	var key_name_act=getKeyName(select_item);
	var arr_to_data=Array();

	for (x=1; x<tab.length; x++){
		if(typeof(tab[x])!='undefined' ){
			id_lang_x=tab[x][2];
			value =getElement('txt_trans_'+id_lang_x).value;
			//&& value != tab[x][0] &&
			if(tab[x][1]!= 2  && value!=""){
				if(value=="" || value==null){
					id_status=0;
				}else{
					id_status=1;
				}
				arr_to_data[id_lang_x]=Array();
				arr_to_data[id_lang_x][0]=id_lang_x;//Id Langue
				
				if(unicode_or_utf8=='utf8'){
					//UTF8
					arr_to_data[id_lang_x][1]=addslashes(value);//Translation				
				}else{
					//Unicode
					arr_to_data[id_lang_x][1]=escape(value);//Translation 
				}
				arr_to_data[id_lang_x][2]=id_status;//Status
			}
		}
	}

	sauverMod(id_key,1,'',0,param,key_name_act,without_propagation,arr_to_data);
	
	//calculStats();	
	return false;
}


//Objet XMLHTTPRequest
var XHR = null;

//Fonction de sauvegarde des modifications apportes
function sauverMod(id_key, id_lang, translation, id_status,type,keyname,without_propagation,arr_to_data)
{
	if(XHR && XHR.readyState != 0){	//Si l'objet existe dj on abandonne la requte et on le supprime
		XHR.abort();
		delete XHR;
	}

	XHR = getXMLHTTP(); //Cration de l'objet XMLHTTPRequest
	if(!XHR){
		return false;
	}
	
	if(type=="update"){
		if(unicode_or_utf8=='utf8'){
			/* UTF8 */
			values=serialize(arr_to_data);
		}else{
			/* unicode */
			values=serialize2(arr_to_data);
		}
		//Remove id_key
		XHR.open("GET", "./includes/savedata_much.php?id_key=" + id_key + "&type=" + type + "&without_propagation=" + without_propagation +"&values="+base64_encode(values));		
	}else{
		//Remove keyname
		XHR.open("GET", "./includes/savedata.php?id_key=" + id_key + "&id_lang=" + id_lang + "&translation=" + escape(translation) + "&id_status=" + id_status +"&type="+type+"&keyname="+keyname);
	}
	
	test = undefined;
	setTimeout('var test = function(){ alert("Thank you"); }', 10);
	var Start = (new Date()).getTime();
	while(typeof test != 'function') {
	  if( ((new Date()).getTime() - Start) > 300 ){
		//alert('test definitly undefined');
		not="ok";
		break;
	  }
	}
	if(typeof test == 'function') test();
		
	//On se sert de l'evnement OnReadyStateChange pour supprimer l'input et le replacer par son contenu
	XHR.onreadystatechange = function(){
		if (XHR.readyState == 4){//Si le chargement est termin
			if(XHR.status==200 ){
				if(type=="update"){
					return_arr= eval("(" + XHR.responseText + ")");
					for(x in return_arr){
						changeStatusUp(return_arr[x][0],return_arr[x][3],id_key,return_arr[x][1],return_arr[x][2],type);
					}
				}else{					
					if(XHR.responseText=="nothing"){
						changeStatusUp(id_status,id_lang,id_key,translation,my_email,type,false);				
					}else{
						myData= eval("(" + XHR.responseText + ")");
						changeStatusUp(myData[0],id_lang,id_key,myData[1],myData[2],type,false);				
					}
					//calculStats();
				}
			}
		}
	}
	XHR.send(null);//Envoi de la requte
}

function changeStatusUp(status,id_lang,id_key,translation,email,type){
	select_item=parseInt(getElement('item_select').value);
	if(unicode_or_utf8=='unicode'){
		/* Only for Unicode */
		translation=unescape(translation.replace(/&#x/g,'%u'));
	}
	arr[id_key][id_lang][0]=translation;
	arr[id_key][id_lang][1]=id_status;
	if(status==0 && translation==''){
		arr[id_key][id_lang][4]='';
		arr[id_key][id_lang][5]='';
	}else if(status==1 && arr[id_key][id_lang][4]==''){
		arr[id_key][id_lang][4]=email;
	}else if(status==1 && type=="update"){		
		arr[id_key][id_lang][5]=my_email;
	}else if(status==1){		
		arr[id_key][id_lang][5]=email;
	}

	getElement("txt_trans_"+id_lang).value=translation;
	getElement("img_status_tab_"+id_key+"_"+id_lang).src=getSrcLogoStatus(id_status);

	groupe=getElement('group_user').value;
	if(status==1 || status==2){
		getElement("txt_trans_"+id_lang).disabled="disabled";
		getElement("lbl_trans_by_"+id_lang).innerHTML="By "+arr[id_key][id_lang][4];
		
		if(arr[id_key][id_lang][5]!=''){
			getElement("lbl_trans_by_"+id_lang).innerHTML="By "+arr[id_key][id_lang][4]+", Edited by "+arr[id_key][id_lang][5];
		}
	}else if(status==0){
		getElement("txt_trans_"+id_lang).disabled="";	
	}
	
	//When reset us langue => Rest all langue
	if(type=="reset" && id_lang==1){
		key_word=getIdKeyName(select_item);
		for(x in arr[key_word]) {
			if(arr[key_word][x][1]==2 && x!=1 && x!=0){
				arr[key_word][x][1]=1; //status=1
				getElement("img_status_tab_"+id_key+"_"+x).src=getSrcLogoStatus(1);
			}
		}
	}
	changeItems(select_item);
}

//Function to change items with traduction 
function changeItems(num_item){
	key_word=getIdKeyName(num_item);
	if(groupe==null)groupe=getElement('group_user').value;
	getElement("lbl_key_name").innerHTML=arr[key_word]['0'][0];
	getElement("index_key").innerHTML=num_item;
	index_desc=arr[key_word]['0'][2].indexOf("{desc}");
	text_desc=arr[key_word]['0'][2].substr(index_desc+8);
	text_file_name=arr[key_word]['0'][2].substr(0,index_desc);
	getElement("file_name").innerHTML=text_file_name;
	if(text_desc=='' || text_desc==null){
		getElement("file_desc").className='cachediv';
	}else{
		getElement("file_desc").className='';
		getElement("desc_file").innerHTML=text_desc;
	}
	getElement("saveTranslation").className="";

	//if(arr[key_word][1]['1']==1)history.go(0);
	for(x in arr[key_word]) { 
		if(x!='0'){
			if(unicode_or_utf8=='unicode'){
				/* Only for Unicode */
				arr[key_word][x][0]=unescape(arr[key_word][x][0]);
			}
			getElement("img_status_"+x).src=getSrcLogoStatus(arr[key_word][x][1]);
			getElement("txt_trans_"+x).value=arr[key_word][x][0];
			getElement("lbl_trans_"+x).innerHTML=arr[key_word][x][0].replace("<","&lt;");
			getElement("lbl_trans_by_"+x).innerHTML="By "+arr[key_word][x][4];
			if((my_email==arr[key_word][x][4] || my_email==arr[key_word][x][5]) && arr[key_word][x][0]!='' && arr[key_word][x][1]==1 && groupe!="staff" && groupe!="admin"){
				getElement("edit_my_item_"+x).className="";				
			}else{
				getElement("edit_my_item_"+x).className="cachediv";
			}
			
			if(arr[key_word][x][5]!=''){
				getElement("lbl_trans_by_"+x).innerHTML="By "+arr[key_word][x][4]+", Edited by "+arr[key_word][x][5];
			}
			getElement("lbl_trans_alert_"+x).className="cachediv";
			
			if(arr[key_word][x][1]==2){
				classTxt="cachediv";
				classLbl="";
				if(groupe=="admin" || groupe=="staff"){ 
					getElement("btn_reset_"+x).className="";
				}else{
					if(typeof(getElement("btn_reset_"+x))!='undefined' ){
						getElement("btn_reset_"+x).className="cachediv";
					}
				}
			}else if(arr[key_word][x][1]==1 || arr[key_word][x][1]==0){
				classLbl="cachediv";
				classTxt="";
			}

			if(arr[key_word][x][1]==1){
				getElement("txt_trans_"+x).disabled="disabled";
				if(typeof(getElement("btn_reset_"+x))!='undefined' ){
					getElement("btn_reset_"+x).className="cachediv";
				}
			}else{
				getElement("txt_trans_"+x).disabled="";
			}
			if(arr[key_word][x][1]==0){
				if(typeof(getElement("btn_reset_"+x))!='undefined' ){
					getElement("btn_reset_"+x).className="cachediv";
				}
			}
			if(arr[key_word][x][1]==1 && (groupe=="admin" || groupe=="staff")){
				getElement("btn_validate_"+x).className="";
				getElement("img_status_cont_"+x).className="cachediv";
				getElement("btn_validate_refused_"+x).className="";
			}else{
				getElement("img_status_cont_"+x).className="";
				if(typeof(getElement("btn_validate_refused_"+x))!='undefined' ){
					getElement("btn_validate_refused_"+x).className="cachediv";
				}
			}
			if((groupe=="admin" || groupe=="staff") && arr[key_word][x][1]==2 && x!=1 ){
				getElement("btn_reset_"+x).className="";
			}
			
			//Demasque le bouton save si l'anglais est vide
			if(groupe!="admin" && groupe!="staff" && arr[key_word][x][1]<1 && x==1){
				getElement("saveTranslation").className="cachediv";
			}
			
			getElement("cont_txt_"+x).className=classTxt;
			getElement("lbl_trans_"+x).className=classLbl;
			changeNbrChars(x,arr[key_word][x][1]);
		}							
	} 
}


//Function to save variable session
function setSessionValue(name, value){
	if(XHR && XHR.readyState != 0){
		XHR.abort();
		delete XHR;
	}	
	XHR = getXMLHTTP(); 
	if(!XHR){
		return false;
	}	
	XHR.open("GET", "./includes/session.php?name="+name+"&value=" + value);
	XHR.send(null);	
}


//Function to validate\refuse Translation
function validateTransWord(param,lang){
	select_item=parseInt(getElement('item_select').value);
	var tab = getLineValues(select_item);
	id_key=getIdKeyName(select_item);
	
	value =getElement('txt_trans_'+lang).value;
	if(param=="validate"){id_status=2;}
	if(param=="refused" || param=="reject"){id_status=0;}
	if(param=="reset"){id_status=1;}
	if(param=="reject"){value="";}

	sauverMod( id_key, lang, value, id_status,param,getKeyName(select_item) );	
	return false;
}


function changeStatus(status,id_lang,id_key,translation){
					
	select_item=parseInt(getElement('item_select').value);
	arr[id_key][id_lang][0]=translation;
	arr[id_key][id_lang][1]=id_status;
	
	getElement("txt_trans_"+id_lang).value=translation;
	//changeItems(select_item);
	//arr[id_key][id_lang][0]=translation;
	//arr[id_key][id_lang][1]=status;
	
	groupe=getElement('group_user').value;
	
	if(status==1){
		getElement("txt_trans_"+id_lang).disabled="disabled";	
	}
	if(status==2){
		getElement("txt_trans_"+id_lang).disabled="disabled";	
	}
	if(status==0){
		getElement("txt_trans_"+id_lang).disabled="";	
	}
}



//Objet XMLHTTPRequest
var XHR1 = null;

//Fonction calcul stats
function calculStats(statusWord)
{
	if(XHR1 && XHR1.readyState != 0){	//Si l'objet existe dj on abandonne la requte et on le supprime
		XHR1.abort();
		delete XHR1;
	}
	
	XHR1 = getXMLHTTP(); //Cration de l'objet XMLHTTPRequest
	if(!XHR1){
		return false;
	}

	XHR1.open("GET", "./includes/stats_sentences.php");
	
	test = undefined;
	setTimeout('var test = function(){ alert("Thank you"); }', 10);
	var Start = (new Date()).getTime();
	while(typeof test != 'function') {
	  if( ((new Date()).getTime() - Start) > 300 ){
		//alert('test definitly undefined');
		not="ok";
		break;
	  }
	}
	if(typeof test == 'function') test();
	
	//On se sert de l'evenement OnReadyStateChange pour supprimer l'input et le replacer par son contenu
	XHR1.onreadystatechange = function(){
		if (XHR1.readyState == 4){//Si le chargement est termin			
			editionEnCours = false;//Rinitialisation de la variable d'tat d'dition
			var reg=new RegExp("[~]+", "g");
			var table=XHR1.responseText.split(reg);
			myData1=eval(table[0]);	
			
			var obj1=getElement("translated_sent");			
			obj1.innerHTML='<option>Translated</option>'+myData1[0];

			if(groupe=="admin" || groupe=="staff"){				
				myData2=eval(table[1]);
				var obj2=getElement("validated_sent");
				obj2.innerHTML='<option>Validated</option>'+myData2[0];
			}
		}
	}
	XHR1.send(null);//Envoi de la requte
}

//Get Logo for status word
function getSrcLogoStatus(id_status){
	
	if(id_status==2){
		return  'img/accept.png';
	}else if(id_status==1){
		return 'img/pencil.png';
	}else if(id_status==0){
		return 'img/white.png';
	}else{
		return 'img/white.png';
	}
}

//function to change next item
function setNextItem(){
	select_item=parseInt(getElement('item_select').value);
	var objsel=getElement('selectPage');
	var valueSelectedPage=parseInt(objsel.selectedIndex+1);//getElement('selectPage').value
	if((select_item+1) > (valueSelectedPage* parseInt(getElement('textShow').value))){
		objsel.selectedIndex=valueSelectedPage;
		check();
	}else{		
		if(select_item%2){
			getElement(select_item).className='row0';
		}else{
			getElement(select_item).className='row1';
		}
		getElement(select_item+1).className='cell_on';		
				
		getElement('item_select').value=select_item+1;		
		setSessionValue('item_select',select_item+1);
		
		changeItems(select_item+1);
	}
	
	select_item=parseInt(getElement('item_select').value);
	return false;
}

//function to change prev item
function setPrevItem(){	
	select_item=parseInt(getElement('item_select').value);
	var objsel=getElement('selectPage');
	var valueSelectedPage=parseInt(objsel.selectedIndex+1);//getElement('selectPage').value
	if( ((select_item-1)<=(valueSelectedPage-1)*parseInt(getElement('textShow').value)) && select_item-1>0){
		objsel.selectedIndex=parseInt(valueSelectedPage-2);
		check();
	}else if(select_item-1>0){
		if(select_item%2){
			getElement(select_item).className='row0';
		}else{
			getElement(select_item).className='row1';
		}
		getElement(select_item-1).className='cell_on';
	
		getElement('item_select').value=select_item-1;
		setSessionValue('item_select',select_item-1);		
	
		changeItems(select_item-1);
	}
	select_item=parseInt(getElement('item_select').value);
	return false;
}

//function : change nbr chars & status lbl
function changeNbrChars(ln,status){
	select_item=parseInt(getElement('item_select').value);
	key=getIdKeyName(select_item);
	maxchar=arr[key][0][1];
	if(status==2){
		getElement('lbl_max_'+ln).className="maxLenghtValide";	
	}else if(getElement('txt_trans_'+ln).value.length<=maxchar){
		getElement('lbl_max_'+ln).className="maxLenghtValideOK";
		getElement("lbl_trans_alert_"+ln).className="cachediv";
	}else{
		getElement('lbl_max_'+ln).className="maxLenghtNotValide";
		getElement("lbl_trans_alert_"+ln).className="";
	}	 
	getElement('lbl_max_'+ln).innerHTML="Length: "+	getElement('txt_trans_'+ln).value.length +" Chars";	
}

function format(input){
	var num = input.value.replace(/\./g,'');
	 if(!isNaN(num)){
		 num = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{9})/g,'$1.');
		 num = num.split('').reverse().join('').replace(/^[\.]/,'');
		 input.value = num;
	 }
	
	 else{ alert('You may enter only numbers in this field!');
		   input.value = input.value.replace(/[^\d\.]*/g,'');
	 }  
}


///////////////////////////////////////////////////////////
////////////////////////Glossary///////////////////////////
///////////////////////////////////////////////////////////

//Change Glossary Word
function changeGlossary(num_item){
	/*key_word=getKeyRef(num_item);
	var tabWord =Array();
	var reg=new RegExp("[,;,:,\\,?,(,),{,},']+", "g");
	tabWord=key_word.split(reg);
	//Get Tab langue Id
	var tabIdLang = getElement('header_lang');
	var theChildren = tabIdLang.getElementsByTagName('td');
	var tabLang=Array();
	for(i=0; i< theChildren.length;i++) {
		tabLang[i]= theChildren[i].getAttribute('name');
	}
	var tabGlos = getElement("lang_glossary");
	while (tabGlos.firstChild) {
	  tabGlos.removeChild(tabGlos.firstChild);
	}
	
	if(typeof(tok)!='undefined' && tok.length>0 && tabWord.length>0){			
		for(y in tok){			
			if(tok[y]!="" && tok[y].length>1){
				for(x in tabWord){//Pour chaque mot
					if(tabWord[x].length>0){
						if(tabWord[x]==tok[y][0][0] || tabWord[x].indexOf(tok[y][0][0])!=-1){
							var elmTr = document.createElement("tr");
							//Crer Les child
							for(lang in tabLang){//pour chaque langue
								//Crer tr
								var elmCell = document.createElement("td");
								var nottext=false;
								for(b in tok[y]){//Pour chaque langue										
									if(tok[y][b][2]==tabLang[lang]){
										var tradCell = document.createTextNode(tok[y][b][1]);
										nottext=true;
									}
								}
								if(nottext==false){
									var tradCell = document.createTextNode(' ');
								}
								elmCell.appendChild(tradCell);
								elmTr.appendChild(elmCell);	
							}
							tabGlos.appendChild(elmTr);
						}
					}
				}
			}
		}
	}*/
	
}



///////////////////////////////////////////////////////////
//////////////////////Guide Lines//////////////////////////
///////////////////////////////////////////////////////////

//Hide GuideLines
function cacheGuidelines(param){
	var objGuide = getElement("guidelines");
	if(param==true){
		objGuide.className='cachediv';		
	}else{
		objGuide.className='';
		objGuide.style.position="absolute";
		objGuide.style.display="inline"; 
	}
	
	setFullHeight('cacherTout');
}

//Check Browser version
function checkBrowser()
{	
	this.ver=navigator.appVersion;
	this.dom=document.getElementById?1:0;
	this.ie7=(this.ver.indexOf("MSIE 7")>-1 && this.dom)?1:0;
	this.ie6=(this.ver.indexOf("MSIE 6")>-1 && this.dom)?1:0;
	this.ie55=((this.ver.indexOf("MSIE 5.5")>-1 || this.ie6) && this.dom)?1:0;
	this.ie5=((this.ver.indexOf("MSIE 5")>-1 || this.ie5 || this.ie6) && this.dom)?1:0;
	this.ie4=(document.all && !this.dom)?1:0;
	this.ns5=(this.dom && parseInt(this.ver) >= 5) ?1:0;
	this.ns4=(document.layers && !this.dom)?1:0;
	this.ie4plus=(this.ie6 || this.ie5 || this.ie4);
	this.ie5plus=(this.ie6 || this.ie5)
	this.bw=(this.ie6 || this.ie5 || this.ie4 || this.ns4 || this.ns5);
	return this;
}

bw = new checkBrowser();

//Show mask
function ShowMasque(id){
	
	var objMasque = getElement(id);
	
	objMasque.className= '';	
	objMasque.style.visibility = 'visible';
	objMasque.style.display = 'block';	
	objMasque.style.overflow = 'visible';	
	
	if(bw.ie6 && !bw.ie7 ){
		objMasque.style.position = 'absolute';
	}
	
	return objMasque;
}

//Hide mask
function CacherMasque(id){
	var objC = getElement(id);
	objC.style.display = 'none';
	objC.style.visibility = 'hidden';
	objC.style.overflow = 'hidden';
}

//Change ClassName
function ChangeClassName(id,newValeur){
	var objCls = getElement(id);
	objCls.className=newValeur;
	return objCls;
}

//Set Height guidelines
function setFullHeight(id){
	var objFH = getElement(id);
	if (document.body){
		var haut = (document.body.offsetHeight);
	}else{
		var haut = (window.innerHeight);
	}
	if(getElement('guidelines').offsetHeight>haut){
		haut=getElement('guidelines').offsetHeight+280;
	}
	if(bw.ie6 && !bw.ie7 ){
		objFH.style.height=(haut)+'px';
	}else{
		objFH.style.height=haut+'px';
	}
	return objFH;
}

//Set Width guidelines
function setFullWidth(id){
	var objFW = getElement(id);
	if (document.body){
		var haut = (document.body.offsetHeight);
	}else{
		var haut = (window.innerHeight);
	}
	if(bw.ie6 && !bw.ie7 ){
		objFW.style.width=(larg)+'px';
	}else{
		objFW.style.width=larg;
	}
	return objFW;
}

//function : edit word
function editTranslated(ln){
	getElement('txt_trans_'+ln).disabled='';
	if(typeof(getElement('btn_validate_'+ln))!='undefined' ){
		getElement('btn_validate_'+ln).className='cachediv';
	}
}

//Add langue
function addLangue(){
	var cont_list_langues=getElement('all_selected_langue');
	var list_lang=getElement('list_langues');
	
	var selected_langue = document.babili.list_langues.selectedIndex;
	var option = document.babili.list_langues.options[selected_langue];	
	var ln_flag=option.id;
	var ln_value=option.value;
	var ln_text=option.text;
	
	var tr = document.createElement("tr");
	tr.setAttribute('id', "cont_div_"+ln_value);

		var td1 = document.createElement("td");		
				
		var hide_value=document.createElement("input");
		hide_value.setAttribute('type', 'hidden');
		hide_value.setAttribute('name', 'lang[]');
		hide_value.value=ln_value;
		
		td1.appendChild(hide_value);
				
		var td2 = document.createElement("td");
		var img = document.createElement('img');
		img.setAttribute('src', ln_flag);

		td2.appendChild(img);
		
		var td3 = document.createElement("td");
		var span = document.createElement('span');
		
		span.innerHTML="&nbsp;"+ln_text+"&nbsp;";
		td3.appendChild(span);
		
		var td4 = document.createElement("td");
		var btn_remove = document.createElement('input');
		
		btn_remove.setAttribute('type', 'button');
		btn_remove.setAttribute('name', 'rm_'+ln_value);
		btn_remove.value="Remove";
		btn_remove.setAttribute('onclick', 'removeLangue(\''+ln_value+'\',\''+ln_text+'\',\''+ln_flag+'\')');
	
		td4.appendChild(btn_remove);
		
		tr.appendChild(td1);
		tr.appendChild(td2);
		tr.appendChild(td3);
		tr.appendChild(td4);
	
	cont_list_langues.appendChild(tr);
	
	document.babili.list_langues.removeChild(option);
}

//Remove langue
function removeLangue(name,text,flag){
	//Add langue to list
	var cont_list_langues=getElement('all_selected_langue');
	var list_lang=getElement('list_langues');
	
	var option = document.createElement("option");
	option.value=name;
	option.innerHTML=text;
	option.setAttribute('id', flag);
	option.setAttribute('text', text);
	option.setAttribute('style', 'background:url(\''+flag+'\') no-repeat right; padding-right:20px');
	
	list_lang.appendChild(option);
	
	//Remove langue
	var tr = getElement("cont_div_"+name);
	var all_selected_langue=getElement('all_selected_langue');
	all_selected_langue.removeChild(tr);	
}

//Clear Search By Date
function emptyByWord(){
	getElement('search_key').value="";
	getElement('search_option_any').checked="checked";	
}

function getObjHeight(idObjH){
	var idObjH = getElement(idObjH);
	var objHeight = null;
	if(document.implementation.hasFeature("CSS", "2.0")) {
		objHeight = document.defaultView.getComputedStyle(idObjH,null).getPropertyCSSValue("height").getFloatValue(5);
	}else if(obj.clientHeight!=null) {
		objHeight = idObjH.offsetHeight;
	}
	return objHeight;
}

//Scroll Tools traduction
function changeTop(e){
	var boardNavigatorH = getObjHeight("boardNavigator");
	var lnTrans= getObjHeight("ln_translations");
	
	var topTools=document.documentElement.scrollTop-(lnTrans/2);
	
	if(topTools<=1){
		topTools=1;
	}
	getElement("col_right").style.paddingTop=(topTools)+"px";
}

/*** Show Menu Langues ***/
function showlayer(layer){
	var myLayer=getElement(layer);
	if(myLayer.style.display=="none" || myLayer.style.display==""){
		myLayer.style.display="block";
	} else { 
		myLayer.style.display="none";
	}
}

/*** Remove table ***/
 var remove=function(){
   if(arguments[1]>0){
     var _temp=arguments[0].splice(0,arguments[1]);
     arguments[0].shift();
     while(_temp.length>0){
        arguments[0].unshift(_temp.pop());
     }
   }
   else{
     arguments[0].shift();
   }
 };


var XHR3=null;
function getItems(action){
	if(XHR3 && XHR3.readyState != 0){	//Si l'objet existe dj on abandonne la requte et on le supprime
		XHR3.abort();
		delete XHR3;
	}
	
	XHR3 = getXMLHTTP(); //Cration de l'objet XMLHTTPRequest
	if(!XHR3){
		return false;
	}

	XHR3.open("GET", "./includes/get.items.php?action="+action);
	
	test = undefined;
	setTimeout('var test = function(){ alert("Thank you"); }', 10);
	var Start = (new Date()).getTime();
	while(typeof test != 'function') {
	  if( ((new Date()).getTime() - Start) > 300 ){
		//alert('test definitly undefined');
		not="ok";
		break;
	  }
	}
	if(typeof test == 'function') test();
	
	//On se sert de l'evenement OnReadyStateChange pour supprimer l'input et le replacer par son contenu
	XHR3.onreadystatechange = function(){
		if (XHR3.readyState == 4){//Si le chargement est termin			
			editionEnCours = false;//Rinitialisation de la variable d'tat d'dition
			var reg=new RegExp("[~]+", "g");
			var table=XHR3.responseText.split(reg);			
			alert(arr);
			remove(arr);
			arr=eval('('+table+')');
			alert(arr);
			//Call function to initialise table
		}
	}
	XHR3.send(null);//Envoi de la requte
	return true;	
}